package it.uniba.di.mas.jpnde.core;

import bsh.Interpreter;
import jade.util.Logger;
import jade.util.leap.ArrayList;
import jade.util.leap.List;
import jade.util.leap.Serializable;

public class ScriptCondition implements Serializable{

	private static final long serialVersionUID = 1L;
	
	public static final int MAX_PRIORITY=1000;
	
	private ArrayList imports=null;
	private ArrayList expressions=null;
	private int priority=MAX_PRIORITY;
	
	private Logger logger=null;
	
	public ScriptCondition(){
		imports=new ArrayList();
		expressions=new ArrayList();
	}

	public void clear(){
		imports=new ArrayList();
		expressions=new ArrayList();
	}
	
	public void addImport(ScriptImport sImport){
		imports.add(sImport);
	}

	public void addExpression(ScriptExpression sExp){
		expressions.add(sExp);
	}

	public int getPriority() {
		return priority;
	}

	public void setPriority(int priority) {
		this.priority = priority;
	}
	
	public boolean eval(int numToken,Token token,List vars)
		throws Exception
	{
		boolean ret=false;
		//System.out.println("num > "+numToken+" > "+token+" > "+vars);
		logger=Logger.getMyLogger(this.getClass().getName());
		
		for(int i=0;i<expressions.size();i++){
			ScriptExpression expr=(ScriptExpression)expressions.get(i);
			if (expr.getNumToken()==-1||expr.getNumToken()==numToken){
				
				Interpreter engine = new Interpreter();
				engine.set("token", token);
				for(int j=0;j<vars.size();j++)
					{
					TaggedValue tv=(TaggedValue)vars.get(j);
					engine.set(tv.getName(), tv.getValue());
					}
				
				engine.eval("import it.uniba.di.mas.jpnde.core.*;");
				
				for(int j=0;j<imports.size();j++){
					ScriptImport sImport=(ScriptImport)imports.get(j);
					String stmt="import "+sImport.getPackage()+";";
					logger.log(Logger.INFO,stmt);
					engine.eval(stmt);
				}
				String stmt="boolean eval=("+(expr.getBody().replaceAll("\n", "")).replaceAll("\r", "")+")";
				logger.log(Logger.INFO,stmt);
				engine.eval(stmt);
				ret=(Boolean)engine.get("eval");
				if (!ret)
					return ret;
			}
		}
		return ret;
	}
	
	public String toString() {
		return "Condition [imports=" + imports +", exps=" + expressions +"]";
	}
}
